/*!
 @header CommentPubViewController.m
 @author 周益
 @version 1.0.0 2013/02/03 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "CommentPubViewController.h"
#import "Helper.h"
#import "Config.h"
#import "JSONRequest.h"
#import "RegexKitLite.h"
#import "JMFBase.h"

static float		g_keyboardFrameHeightLastTime = 216;

//  -业务逻辑细节说明-
//
//  @abstract       CommentPubViewController功能较为简单，发布心情为一个请求；其次是字数统计和汉英切换时的键盘遮挡问题。
//

//  @discussion     字数统计：为组件方法，直接调用即可，不再赘述。
//                汉英切换时的键盘遮挡问题：利用UIKeyboardDidShowNotification和UIKeyboardWillHideNotification两个通知来完成。
//                    每次记录键盘的最后一次的高度（最初为定值216）与键盘此时的高度作对比，如果存在高度差那么表示发生了汉英切换，那么就
//                    以动画的形式上或下调整视图。

//  @notes          要在viewDidDisappear中将g_keyboardFrameHeightLastTime设回初始值，以防下次进入评论页时，键盘会遮挡住部分视图。
//                并且要注销键盘的通知。

//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface CommentPubViewController ()

@end

@implementation CommentPubViewController
@synthesize delegate = _delegate;
@synthesize orderId = _orderId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    //back button bar
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *publishButton = [Helper buttonWithStyle:ButtonStyleNavigationDone];
    [publishButton addTarget:self action:@selector(pulishButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    
    //创建textview，并设置焦点
    _commentTextView = [[UITextView alloc] init];
    _commentTextView.tag = 100;
    _commentTextView.delegate = self;
    _commentTextView.returnKeyType = UIReturnKeyDone;
    [_commentTextView setFont:_SYS_FONT_004];
    _commentTextView.frame = CGRectMake(10, 10, 300, _SYS_FRAME_HEIGHT - 260-44);
    [_commentTextView becomeFirstResponder];
    [self.view addSubview:_commentTextView];
    
    //友好文字
    _friendlyLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 170.0f, 200.0f, 30.0f)];
    
    _friendlyLabel.backgroundColor = [UIColor clearColor];
    _friendlyLabel.text = _L(@"title_11");   //你有什么话想对TA说
    _friendlyLabel.textColor = _SYS_COLOR_003;
    [self.view addSubview:_friendlyLabel];
    
    //设置字数统计
	_viewWordNum = [[WordsLeftView alloc] initWithFrame:CGRectMake(280, 178, 30, 18)];
	[self.view addSubview:_viewWordNum];
    _viewWordNum.backgroundColor = [UIColor clearColor];
	_viewWordNum.wordsNum = MaxInputWords;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    g_keyboardFrameHeightLastTime = 216;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 返回按钮流程

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    if (_commentTextView.text.length > 0) {
        NSString* alertString = _replyCommentId > 0 ? _L(@"alert_99") : _L(@"alert_89");
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:alertString delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    else {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

#pragma mark - 自定义事件
/*!
 @abstract 发布按钮事件
 */
- (void)pulishButtonEvent:(id)sender
{    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_COMMENT_ADD];
    [request setValue:[NSString stringWithFormat:@"%d", _dynamicId] forParameter:@"dynamicId"];
    if (_orderId > 0) {
        [request setValue:[NSString stringWithFormat:@"%d", _orderId] forParameter:@"productOrderId"];
    }
    [request setValue:_commentTextView.text forParameter:@"content"];

    
#warning 此处判断是否是回复一条评论的情况有欠妥当
    if (_replyCommentId > 0) {
        [request setValue:[NSString stringWithFormat:@"%d", _replyCommentId] forParameter:@"replyCommentId"];
        [request setValue:[NSString stringWithFormat:@"%d", _replyUserId] forParameter:@"replyUserId"];
    }
    
    //请求
    NSDictionary *responseData = [request synchronous];
    NSLog(@"%@", responseData);
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
    if (jmf.status == JMStatusSucceed) {
        NSDictionary *data = [responseData objectForKey:@"data"];
        if ([data isKindOfClass:[NSNull class]]) {
            return;
        }
        NSDictionary *dynamicComment = [data objectForKey:@"dynamicComment"];
        if ([dynamicComment isKindOfClass:[NSNull class]]) {
            return;
        }
        
        //评论后，刷新上级视图
        if ([_delegate respondsToSelector:@selector(commentsShouldReload)]) {
            [_delegate commentsShouldReload];
        }
        
        
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

#pragma mark - 键盘消失和显示通知

/*!
 @abstract 键盘即将消失时调用
 @param notification 通知源
 */
- (void)keyboardWillHide:(NSNotification *)notification {
    
    //获得键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    float keyboardHeight = keyboardRect.size.height;
    
    //计算此时的高度和上一次的键盘高度的差异，判断键盘高度是否发生改变，即是否隐藏或者汉英切换
    NSNumber *height = nil;
    height = [[NSNumber alloc] initWithFloat:keyboardHeight - g_keyboardFrameHeightLastTime];
    
    //保存键盘的高度
    g_keyboardFrameHeightLastTime = keyboardHeight;
    
    //height不为0，则高度发生改变
    if ([height intValue] != 0) {
        [self performSelectorOnMainThread:@selector(scrollIfNeeded:) withObject:height waitUntilDone:NO];
    }
}

/*!
 @abstract 键盘出现时调用
 @param notification 通知源
 */
- (void) keyboardWasShown:(NSNotification *) notification {
    [self keyboardWillHide:notification];
}

/*!
 @abstract 键盘中英文切换时，为防止视图被遮挡而视图上下移动
 @param boundsHeight 键盘变化高度差
 */
- (void)scrollIfNeeded:(NSNumber *)boundsHeight {
    
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.3];
    _commentTextView.frame = CGRectMake(_commentTextView.frame.origin.x, _commentTextView.frame.origin.y, _commentTextView.frame.size.width, _commentTextView.frame.size.height - [boundsHeight floatValue]);
    
    _friendlyLabel.frame = CGRectMake(_friendlyLabel.frame.origin.x, _friendlyLabel.frame.origin.y - [boundsHeight floatValue], _friendlyLabel.frame.size.width, _friendlyLabel.frame.size.height);
    _viewWordNum.frame = CGRectMake(_viewWordNum.frame.origin.x, _viewWordNum.frame.origin.y - [boundsHeight floatValue], _viewWordNum.frame.size.width, _viewWordNum.frame.size.height);
    
	[UIView commitAnimations];
    
}

#pragma mark - 公有方法

/*!
 @abstract 设置回复评论的动态id。
 @discussion 此方法被调用的情况是评论动态。
 @param dynamicId 动态id
 */
-(void)setDynamicId:(NSInteger)dynamicId
{
    _dynamicId = dynamicId;
}

/*!
 @abstract 设置评论的动态id，用户id和评论id
 @discussion 此方法被调用的情况是回复一条评论。
 @param dynamicId 动态id
 @param userId 此动态发起者的用户id
 @param commentId 被回复的评论的id
 */
-(void)setDynamicId:(NSInteger)dynamicId andUserId:(NSInteger)userId andCommentId:(NSInteger)commentId
{
    _dynamicId = dynamicId;
    _replyUserId = userId;
    _replyCommentId = commentId;
}

#pragma mark 字数统计相关

// 字数统计
- (int)calcStrWordCount:(NSString *)str {
	int nResult = 0;
	NSString *strSourceCpy = [str copy];
	NSMutableString *strCopy =[[NSMutableString alloc] initWithString: strSourceCpy];
    
    NSArray *array = [strCopy componentsMatchedByRegex:@"((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(\\.[-A-Za-z0-9]+)*(\\.[-A-Za-z]{2,5}))|([0-9]{1,3}(\\.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*)*"];
	if ([array count] > 0) {
		for (NSString *itemInfo in array) {
			NSRange searchRange = {0};
			searchRange.location = 0;
			searchRange.length = [strCopy length];
			[strCopy replaceOccurrencesOfString:itemInfo withString:@"aaaaaaaaaaaa" options:NSCaseInsensitiveSearch range:searchRange];
		}
	}
    
	char *pchSource = (char *)[strCopy cStringUsingEncoding:NSUTF8StringEncoding];
	int sourcelen = strlen(pchSource);
	
	int nCurNum = 0;		// 当前已经统计的字数
	for (int n = 0; n < sourcelen; ) {
		if( *pchSource & 0x80 ) {
			pchSource += 3;		// NSUTF8StringEncoding编码汉字占３字节
			n += 3;
			nCurNum += 2;
		}
		else {
			pchSource++;
			n += 1;
			nCurNum += 1;
		}
	}
	// 字数统计规则，不足一个字(比如一个英文字符)，按一个字算
	nResult = nCurNum / 2 + nCurNum % 2;
	return nResult;
}


// 从字符串中获取字数个数为N的字符串，单字节字符占半个字数，双字节占一个字数
- (NSString *)getSubString:(NSString *)strSource WithCharCounts:(NSInteger)number {
	// 一个字符以内，不处理
	if (strSource == nil || [strSource length] <= 1) {
		return strSource;
	}
	char *pchSource = (char *)[strSource cStringUsingEncoding:NSUTF8StringEncoding];
	int sourcelen = strlen(pchSource);
	int nCharIndex = 0;		// 字符串中字符个数,取值范围[0, [strSource length]]
	int nCurNum = 0;		// 当前已经统计的字数
	for (int n = 0; n < sourcelen; ) {
		if( *pchSource & 0x80 ) {
			if ((nCurNum + 2) > number * 2) {
				break;
			}
			pchSource += 3;		// NSUTF8StringEncoding编码汉字占３字节
			n += 3;
			nCurNum += 2;
		}
		else {
			if ((nCurNum + 1) > number * 2) {
				break;
			}
			pchSource++;
			n += 1;
			nCurNum += 1;
		}
		nCharIndex++;
	}
	assert(nCharIndex > 0);
	return [strSource substringToIndex:nCharIndex];
}


#pragma mark TextVeiw Delegate

// 往textView输入文字时触发
- (void)textViewDidChange:(UITextView *)tView {
	if (tView.tag == 100) {
        
		int textUTF8StrLength = [self calcStrWordCount:_commentTextView.text];
		if (textUTF8StrLength > MaxInputWords + 200) {
			tView.text = [tView.text substringToIndex:MaxInputWords + 200];
		}
		NSInteger charLeft = MaxInputWords - textUTF8StrLength;
        // 修正字个数
        if (charLeft <= 0) {
            [_viewWordNum setWordsNum:0];
            // 文字内容大于140字，提示
            UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle: _L(@"alert_24")
                                                              delegate:nil cancelButtonTitle:nil
                                                destructiveButtonTitle:_L(@"btn_yes_01") otherButtonTitles:nil, nil];
            [menu showInView:self.view];
            
        }else {
            [_viewWordNum setWordsNum:charLeft];
        }
        
    }
}

// textView中不直接输入字而改变内容的时候触发
- (void)textViewDidBeginEditing:(UITextView *)textV {
    if (textV.tag == 100) {
		int textUTF8StrLength = [self calcStrWordCount:_commentTextView.text];
		if (textUTF8StrLength > MaxInputWords + 200) {
			textV.text = [_commentTextView.text substringToIndex:MaxInputWords + 200];
		}
		NSInteger charLeft = MaxInputWords - textUTF8StrLength;
        // 修正字个数
        [_viewWordNum setWordsNum:charLeft];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        
        [self pulishButtonEvent:nil];
        
        return NO;
    }
    
    return YES;
}


@end
